package tbdp.tool.writer;

import com.google.common.base.Joiner;

import org.apache.commons.io.IOUtils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import tbdp.tool.common.ColumnDesc;
import tbdp.tool.common.JobConstants;
import tbdp.tool.common.Record;
import tbdp.tool.context.JobContext;
import tbdp.tool.format.csv.CsvFormatter;
import tbdp.tool.spi.RecordIterator;
import tbdp.tool.spi.Writer;

/**
 * @author xbkaishui
 * @version $Id: CsvWriter.java, v 0.1 2017-06-18 下午12:49 xbkaishui Exp $$
 */
public class CsvWriter extends Writer {

    private CsvFormatter csvFormater = new CsvFormatter();

    /**
     * 读取数据写入的文件里面
     */
    @Override
    public void write(JobContext context, RecordIterator recordIterator) {
        String tmpFilePath = getTmpFilePath(context);
        OutputStream oos = null;
        PrintWriter writer = null;
        try {
            oos = new FileOutputStream(tmpFilePath);
            writer = new PrintWriter(oos);
            while (recordIterator.hasNext()) {
                Record record = (Record) recordIterator.next();
                List<Object> values = csvFormater.format((ColumnDesc[]) context.getValue(JobConstants.COLUMN_SCHEMA), record);
                String line = Joiner.on(",").join(values);
                writer.println(line);
            }
        } catch (Throwable e) {
            logger.error("CsvWriter error", e);
        } finally {
            IOUtils.closeQuietly(writer);
            IOUtils.closeQuietly(oos);
        }
    }

    @Override
    public void close(JobContext context) {
    }

    @Override
    public String getType() {
        return "csv";
    }
}
